package com.kly.controller;

import com.kly.common.BaseResponse;
import com.kly.common.ResultUtils;
import com.kly.exception.BusinessException;
import com.kly.exception.ErrorCode;
import com.kly.manager.CosManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;

/**
 * @author admin
 * @date 2025/3/3
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {

    @Resource
    private CosManager cosManager;

    @PostMapping("/upload")
    public BaseResponse<String> uploadFile(@RequestPart("file") MultipartFile file) {
        //     获取文件名
        String fileName = file.getOriginalFilename();
        String key = "other";
        File tempFile = null;
        try {
            //     创建临时文件
            tempFile = File.createTempFile("my-temp", "");
            file.transferTo(tempFile);
            //     上传文件到 COS
            String url = cosManager.uploadFile(key, fileName, tempFile);
            return ResultUtils.success(url);
        } catch (Exception e) {
            log.error("上传文件失败", e);
        } finally {
            if (tempFile != null) {
                tempFile.delete();
            }
        }
        throw new BusinessException(ErrorCode.OPERATION_ERROR, "上传失败");
    }

}
